<?php

class userManageActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    public function executeList(sfWebRequest $request) {
        $types = UserTable::getUserTypes();
        $this->types = $types;

        $storeId = $request->getParameter('storeId', 0);
        $stores = StoreTable::getForSelect();
        $this->stores = $stores;
        $this->storeId = $storeId;

        $isActive = $request->getParameter('isActive', 1);
        $this->isActive = $isActive;

        $name = $request->getParameter('name', null);
        $this->name = $name;

        $rows = UserTable::getList($storeId, $isActive, $name);
        $this->rows = $rows;
    }

    public function executeUpdate(sfWebRequest $request) {
        $id = $request->getParameter('id');
        $type = $request->getParameter('t');

        if ($id) {
            $user = UserTable::retrieveByPK($id);
            if (!$user) {
                $this->getUser()->setFlash('warning', 'Ажилтан олдсонгүй');
                $this->redirect($request->getReferer());
            }
            $flash = 'Амжилттай заслаа';
        } else {
            $user = new User();
            $flash = 'Амжилттай нэмлээ';
        }

        if ($type) {
            $user['type'] = $type;
        }

        $form = new UserForm($user);

        if ($request->isMethod('post')) {
            $form->bind($request->getParameter('user'));
            $pass = $form->getValue('pass');

            if ($form->isValid()) {
                if ($form->isNew()) {
                    $form->getObject()->setPassword(md5($pass));
                } else {
                    if ($pass != '') {
                        $form->getObject()->setPassword(md5($pass));
                    }
                }
                $form->save();

                $this->getUser()->setFlash('success', $flash);
                $this->redirect('@user_list');
            }
        }

        $this->form = $form;
        $this->id = $id;
        $this->user = $user;
    }

    public function executeChangeState(sfWebRequest $request) {
        $user = UserTable::retrieveByPk($request->getParameter('id'));
        if ($user) {
            if ($user->is_active == UserTable::ACTIVE) {
                $user->setIsActive(UserTable::PASSIVE);
                $this->getUser()->setFlash('success', 'Амжилттай устгалаа');
            } elseif ($user->is_active == UserTable::PASSIVE) {
                $user->setIsActive(UserTable::ACTIVE);
                $this->getUser()->setFlash('success', 'Амжилттай сэргээлээ');
            }
            $user->save();
        } else {
            $this->getUser()->setFlash('error', 'Ажилтан олдсонгүй!');
        }

        $this->redirect('@user_list');
    }

}
